package com.ffs.game.http;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpUtil;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ffs80
 * @date 2022/4/4 19:47
 */
public class Request {
    /**
     * 请求参数
     */
    private Map<String, String> parameters = new HashMap<>();
    /**
     * net URI
     */
    private URI uri;
    /**
     * 请求方式
     */
    private HttpMethod httpMethod;
    /**
     * 请求api地址
     */
    private String path;
    /**
     * http请求构造
     */
    private FullHttpRequest msg;
    /**
     * 连接通道
     */
    private Channel channel;
    /**
     * http keepAlive参数
     */
    private boolean keepAlive;
    /**
     * 是否已完成参数解析
     */
    private boolean parameterParsed;

    public Request(FullHttpRequest msg, Channel channel) throws URISyntaxException {
        this.msg = msg;
        this.channel = channel;
        this.uri = new URI(msg.uri());
        this.path = this.uri.getPath();
        this.httpMethod = msg.method();
    }

    /**
     * 请求返回
     */
    public void sendResponse(Response response) {
        if (HttpUtil.isKeepAlive(this.msg)) {
            channel.writeAndFlush(response);
        } else {
            response.setKeepAlive(this.keepAlive);
            channel.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        }
    }

    /**
     * 解析参数
     */
    private void parseParameters() {
        parameterParsed = true;
    }
}
